
#include "QSslServer.h"
QSslServer::QSslServer(QObject *parent)
    : QTcpServer(parent) {
    // 加载私钥和证书
    QFile keyFile("/home/lighthouse/cpp/sslserver/server.key");
    QFile certFile("/home/lighthouse/cpp/sslserver/server.crt");

    if (!keyFile.open(QIODevice::ReadOnly)) {
        qCritical() << "Failed to open private key file.";
        return;
    }
    if (!certFile.open(QIODevice::ReadOnly)) {
        qCritical() << "Failed to open certificate file.";
        return;
    }

    m_key = QSslKey(&keyFile, QSsl::Rsa);
    m_certificate = QSslCertificate(&certFile);

    if (m_key.isNull() || m_certificate.isNull()) {
        qCritical() << "Failed to load SSL key or certificate.";
    }

    clientCertMap.insert("1", "lovy");
    clientCertMap.insert("2", "sun");
    clientCertMap.insert("3", "rose");
}

void QSslServer::incomingConnection(qintptr socketDescriptor) {

    // 创建 QSslSocket 并配置 SSL
    QSslSocket *sslSocket = new QSslSocket(this);
    if (sslSocket->setSocketDescriptor(socketDescriptor)) {
        sslSocket->setPrivateKey(m_key);
        sslSocket->setLocalCertificate(m_certificate);
        QList<QSslCertificate> caCertificates = QSslCertificate::fromPath("/home/lighthouse/cpp/sslserver/ca.crt");

        if (!caCertificates.isEmpty()) {
            // 获取当前的 SSL 配置
            QSslConfiguration sslConfig = sslSocket->sslConfiguration();

            // 将 CA 证书添加到配置中
            sslConfig.setCaCertificates(caCertificates);

            // 设置更新后的 SSL 配置
            sslSocket->setSslConfiguration(sslConfig);

            qDebug() << "CA certificate loaded and added to SSL configuration.";
        } else {
            qWarning() << "CA certificate not found!";
        }

        sslSocket->setPeerVerifyMode(QSslSocket::VerifyPeer); // 根据需求配置验证模式
        sslSocket->setProtocol(QSsl::TlsV1_2OrLater); // 根据需求设置协议版本

        // 开始 SSL 握手
        connect(sslSocket, &QSslSocket::encrypted, this, [sslSocket]() {
            qDebug() << "SSL handshake completed for socket:" << sslSocket->socketDescriptor();
        });

        connect(sslSocket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors),
                this, [sslSocket](const QList<QSslError> &errors) {
                    qDebug() << "SSL errors occurred:" << errors;
                    // 根据需求处理 SSL 错误
                    // sslSocket->ignoreSslErrors(); // 忽略错误
                });

        sslSocket->startServerEncryption();
        if(sslSocket->waitForEncrypted()){
            // 获取客户端证书
            QSslCertificate clientCert = sslSocket->peerCertificate();

            if (!clientCert.isNull()) {
                QString commonName;
                QStringList commonNameList = clientCert.subjectInfo(QSslCertificate::CommonName);
                if (!commonNameList.isEmpty()) {
                    commonName = commonNameList.first();
                } else {
                    qWarning() << "Common Name not found in certificate!";
                }

                if (clientCertMap.contains(commonName)) {
                    QString clientTag = clientCertMap.value(commonName);
                    sslSocket->setProperty("clientTag", clientTag);
                    qDebug() << "Client connected. Tag:" << clientTag;
                } else {
                    sslSocket->setProperty("clientTag", "Unknown");
                    qDebug() << "Unknown client connected. CN:" << commonName;
                }
            } else {
                qDebug() << "Client certificate is null.";
            }
        }

        // 发出信号，通知新连接
        emit newSslConnection(sslSocket);
    } else {
        qWarning() << "Failed to set socket descriptor for QSslSocket.";
        delete sslSocket;
    }
}